package br.ufsc.ctc.ine5622.compilador.arquivo;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Observable;

/**
 * This class is the interface for writing files in the filesystem.
 * 
 * @author William di Domenico
 * @author Paulo Pinho
 * 
 */

public class InterfaceArquivo extends Observable {

	/**
	 * Saves a string to a file
	 * 
	 * @param conteudo
	 *            The content of the file, that is: the text to be saved
	 * @param nomeArquivo
	 *            The filename, with absolute path
	 * @param extensao
	 *            The extension of the file
	 * @return The filename, with absolute path
	 * @throws IOException
	 */
	public String salvar(String conteudo, String nomeArquivo, Extensao extensao)
			throws IOException {

		String nomeAbsoluto = nomeArquivo;

		if (nomeArquivo.endsWith(extensao.toString().toLowerCase()) == false) {
			nomeAbsoluto = nomeArquivo + "."
					+ extensao.toString().toLowerCase();
		}
		BufferedWriter saida = new BufferedWriter(new FileWriter(nomeAbsoluto));

		saida.write(conteudo);
		saida.close();

		return nomeAbsoluto;
	}

	/**
	 * Reads a file from the filesystem
	 * 
	 * @param nomeArquivo
	 *            The filename, with preceding absolute path, to be read
	 * @return The content of the file
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public String ler(String nomeArquivo) throws FileNotFoundException,
			IOException {
		File arquivo = new File(nomeArquivo);
		BufferedReader entrada = new BufferedReader(new FileReader(arquivo));
		char[] cbuf = new char[(int) arquivo.length()];

		entrada.read(cbuf, 0, (int) arquivo.length());

		return new String(cbuf);
	}
}